package com.b2c.erp.controller.zbj;

import com.alibaba.fastjson.JSONObject;
import com.b2c.entity.api.ApiResult;
import com.b2c.common.utils.DateUtil;
import com.b2c.entity.result.EnumResultVo;
import com.b2c.entity.zbj.LiveDataEntity;
import com.b2c.entity.zbj.LiveExpensesEntity;
import com.b2c.erp.DataConfigObject;
import com.b2c.erp.utils.ExcelToHtml;
import com.b2c.interfaces.LiveDataService;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.yaml.snakeyaml.util.UriEncoder;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

@RequestMapping("/zbj")
@Controller
public class LiveDataController {
    private static Logger log = LoggerFactory.getLogger(LiveDataController.class);
    @Autowired
    private LiveDataService liveDataService;
    /**
     * 直播数据list
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/live_data_list", method = RequestMethod.GET)
    public String liveDataList(Model model, HttpServletRequest request){
        Integer pageIndex = 1, pageSize = DataConfigObject.getInstance().getPageSize();
        if (!StringUtils.isEmpty(request.getParameter("page"))) {
            pageIndex = Integer.parseInt(request.getParameter("page"));
        }
        String authorAccount=null;
        if(!StringUtils.isEmpty(request.getParameter("authorAccount"))) {
            authorAccount = request.getParameter("authorAccount");
            model.addAttribute("authorAccount",authorAccount);
        }

        var result = liveDataService.getList(pageIndex,pageSize,authorAccount);
        model.addAttribute("totalSize", result.getTotalSize());
        model.addAttribute("lists", result.getList());
        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("pageSize", pageSize);

        model.addAttribute("view", "livedata");
        model.addAttribute("pView", "sale");
        if(!StringUtils.isEmpty(request.getParameter("msg"))) {
            model.addAttribute("msg",request.getParameter("msg"));
        }
        return "zbj/live_data_list";
    }

    /**
     * 直播复盘
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/live_data_replay",method = RequestMethod.GET)
    public String liveReplay(Model model,HttpServletRequest request,@RequestParam Long id) throws IOException {

//        // 第一种：获取类加载的根路径   D:\git\daotie\daotie\target\classes
//        String path = this.getClass().getResource("/").getPath();
//        System.out.println(path);
//        String arg1 = path+"\\static\\直播复盘表2022.xlsx";
//        StringBuilder stringBuilder = new StringBuilder();
//        // 打印实现Appendable 接口，可打印到stringbuilder、stringbuffer、BufferedWriter等
//        ExcelToHtml excelToHtml = ExcelToHtml.create(arg1, stringBuilder);
//        excelToHtml.setCompleteHTML(true);// 是否打印完整html
//        excelToHtml.printPage();// 打印
//        System.out.println(stringBuilder.toString());// 输出打印结果
//        return stringBuilder.toString();
        var entity = liveDataService.getLiveById(id);
        if(entity != null) {
            if(StringUtils.isEmpty(entity.getRepalyFilePath())==false) {
                try {
                    StringBuilder stringBuilder = new StringBuilder();
                    String path = this.getClass().getResource("/").getPath() + File.separator;
                    log.info("读取文件"+path+entity.getRepalyFilePath());
                    // 打印实现Appendable 接口，可打印到stringbuilder、stringbuffer、BufferedWriter等
                    ExcelToHtml excelToHtml = ExcelToHtml.create(path+entity.getRepalyFilePath(), stringBuilder);
                    excelToHtml.setCompleteHTML(true);// 是否打印完整html
                    excelToHtml.printPage();// 打印
                    model.addAttribute("replayHtml",stringBuilder.toString() );
                } catch (Exception e) {
                    log.error("读取文件失败"+e.getMessage());
                }
            }
            model.addAttribute("liveId", id);
        }
        model.addAttribute("view", "livedata");
        model.addAttribute("pView", "fx");
        return "zbj/live_data_replay";
    }

    /**
     * 直播间数据导入
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/live_data_import", method = RequestMethod.GET)
    public String liveDataImport(Model model, HttpServletRequest request){
        String msg = request.getParameter("msg");
        model.addAttribute("msg",msg);
        model.addAttribute("view", "livedata");
        model.addAttribute("pView", "fx");
        return "zbj/live_data_import";
    }

    /**
     * 直播间数据导入POST
     * @param file
     * @param req
     * @return
     * @throws IOException
     * @throws InvalidFormatException
     */
    @RequestMapping(value = "/live_data_import", method = RequestMethod.POST)
    public Object zhubo_order_import_excel_settle(@RequestParam("excel") MultipartFile file, HttpServletRequest req) throws IOException, InvalidFormatException {
        String fileName = file.getOriginalFilename();
        if(StringUtils.isEmpty(fileName)){
            log.error("没有选择文件");
            return "redirect:/zbj/live_data_import?msg="+ UriEncoder.encode("没有选择文件");
        }else if(fileName.substring(fileName.indexOf(".")+1,fileName.length()).toLowerCase().equals("xlsx")==false){
            log.error("文件不是xlsx文件");
            return "redirect:/zbj/live_data_import?msg="+ UriEncoder.encode("文件不是xlsx文件");
        }

        String dir = System.getProperty("user.dir");
        File destPath = new File( dir + File.separator );
        if (!destPath .exists() && !destPath .isDirectory()){
            log.info("文件夹"+dir + File.separator+"不存在，创建");
            destPath.mkdir();
        }

        String destFileName = dir + File.separator + "uploadedfiles_" + fileName;
//        System.out.println(destFileName);
        File destFile = new File(destFileName);
        file.transferTo(destFile);
        log.info("/***********直播间数据导入，文件后缀" + destFileName.substring(destFileName.lastIndexOf(".")) + "***********/");

        XSSFSheet sheet;
        InputStream fis = null;

        fis = new FileInputStream(destFileName);

        //直播数据list
//        List<LiveDataEntity> list = new ArrayList<>();
        int successCount = 0;
        int existCount = 0;
        int errorCount = 0;
        XSSFWorkbook workbook = null;
        try {
            workbook = new XSSFWorkbook(fis);
            log.info("/***********直播间数据导入***读取excel文件成功***********/");

            sheet = workbook.getSheetAt(0);

            int lastRowNum = sheet.getLastRowNum();//最后一行索引


            //循环读取excel数据
            for (int i = 1; i <= lastRowNum; i++) {
                XSSFRow row  = sheet.getRow(i);
                LiveDataEntity vo = new LiveDataEntity();
                vo.setAuthorImg(row.getCell(0).getStringCellValue());
                vo.setAuthorName(row.getCell(1).getStringCellValue());
                vo.setAuthorAccount(row.getCell(2).getStringCellValue());
                vo.setLiveStartTime(row.getCell(3).getStringCellValue());
                vo.setLiveEndTime(row.getCell(4).getStringCellValue());
                vo.setLiveTime(Float.parseFloat(row.getCell(5).getStringCellValue()));
                vo.setShowUV(Long.parseLong(row.getCell(6).getStringCellValue()));
                vo.setShowPV(Long.parseLong(row.getCell(7).getStringCellValue()));
                vo.setUV(Long.parseLong(row.getCell(8).getStringCellValue()));
                vo.setPV(Long.parseLong(row.getCell(9).getStringCellValue()));
                vo.setPCU(Long.parseLong(row.getCell(10).getStringCellValue()));
                vo.setACU(Long.parseLong(row.getCell(11).getStringCellValue()));
                try {
                    vo.setTS(Float.parseFloat(row.getCell(12).getStringCellValue()));
                }catch (Exception e1){
                    vo.setTS(Float.parseFloat(row.getCell(12).getNumericCellValue() + ""));
                }
                vo.setComments(Long.parseLong(row.getCell(13).getStringCellValue()));
                vo.setXjt(Long.parseLong(row.getCell(14).getStringCellValue()));
                vo.setXzfs(Long.parseLong(row.getCell(15).getStringCellValue()));
                vo.setQgfs(Long.parseLong(row.getCell(16).getStringCellValue()));
                vo.setKbfszb(Double.parseDouble(row.getCell(17).getStringCellValue()));
                vo.setGoodsCount(Long.parseLong(row.getCell(18).getStringCellValue()));
                vo.setGoodsShow(Long.parseLong(row.getCell(19).getStringCellValue()));
                vo.setGoodsClick(Long.parseLong(row.getCell(20).getStringCellValue()));
                vo.setGoodsShowTotal(Long.parseLong(row.getCell(21).getStringCellValue()));
                vo.setGoodsClickTotal(Long.parseLong(row.getCell(22).getStringCellValue()));
                vo.setOrderCount(Long.parseLong(row.getCell(23).getStringCellValue()));
                try {
                    vo.setOrderAmount(Double.parseDouble(row.getCell(24).getStringCellValue()));
                }catch (Exception e2){
                    vo.setOrderAmount(Double.parseDouble(row.getCell(24).getNumericCellValue()+""));
                }
                vo.setOrderGoodsCount(Long.parseLong(row.getCell(25).getStringCellValue()));
                vo.setOrderUser(Long.parseLong(row.getCell(26).getStringCellValue()));
                vo.setOrderRefundCount(Long.parseLong(row.getCell(27).getStringCellValue()));
                try {
                    vo.setOrderRefundAmount(Double.parseDouble(row.getCell(28).getStringCellValue()));
                }catch (Exception e3){
                    vo.setOrderRefundAmount(Double.parseDouble(row.getCell(28).getNumericCellValue()+""));
                }
                vo.setOrderRefundUser(Long.parseLong(row.getCell(29).getStringCellValue()));
                try {
                    vo.setCommission(Double.parseDouble(row.getCell(30).getStringCellValue()));
                }catch (Exception e4){
                    vo.setCommission(Double.parseDouble(row.getCell(30).getNumericCellValue()+""));
                }
                vo.setGoodsClickRate(Double.parseDouble(row.getCell(31).getStringCellValue()));
                vo.setGoodsClickRate2(Double.parseDouble(row.getCell(32).getStringCellValue()));
                vo.setGoodsClickTransactionRate(Double.parseDouble(row.getCell(33).getStringCellValue()));
                vo.setGoodsClickTransactionRate2(Double.parseDouble(row.getCell(34).getStringCellValue()));
                vo.setViewTransactionRate(Double.parseDouble(row.getCell(35).getStringCellValue()));
                vo.setViewTransactionRate2(Double.parseDouble(row.getCell(36).getStringCellValue()));
                vo.setPreOrderCount(Long.parseLong(row.getCell(37).getStringCellValue()));
                try {
                    vo.setPreOrderAmount(Double.parseDouble(row.getCell(38).getStringCellValue()));
                }catch (Exception e5){
                    vo.setPreOrderAmount(Double.parseDouble(row.getCell(38).getNumericCellValue()+""));
                }
                log.info("/***********直播间数据导入***读取excel文件"+i+"行："+ JSONObject.toJSONString(vo) +"***********/");
                var result = liveDataService.addLiveData(vo);
                if(result.getCode() == EnumResultVo.SUCCESS.getIndex()){
                    successCount += 1;
                    log.info("添加成功，ID："+result.getData());
                }else if(result.getCode() == EnumResultVo.NotFound.getIndex()){
                    existCount += 1;
                    log.info("已存在");
                }else {
                    errorCount += 1;
                    log.info("/***********直播间数据导入***出现异常：" + result.getMsg() + "***********/");
//                    return "redirect:/zbj/live_data_import?msg="+ UriEncoder.encode(result.getMsg());
                }

            }


        }catch (Exception e){
            log.info("/***********直播间数据导入***出现异常：" + e.getMessage() + "***********/");
            return "redirect:/zbj/live_data_import?msg="+ UriEncoder.encode(e.getMessage());
        }
        String msg = "成功导入"+successCount+"条直播数据，已存在："+existCount+"，错误："+errorCount;
        log.info(msg);
        return "redirect:/zbj/live_data_list?msg="+UriEncoder.encode(msg);
//        return new ApiResult<>(EnumResultVo.SUCCESS.getIndex(),"成功",list);
    }


    /**
     * 直播营销费用编辑
     * @param model
     * @param id
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/live_marketing_expenses_edit",method = RequestMethod.GET)
    public String edit_zhibo(Model model,@RequestParam Long id,HttpServletRequest request) throws Exception {
        var entity = liveDataService.getLiveExpensesByLiveId(id);
        model.addAttribute("entity",entity);
        model.addAttribute("id",id);
        if(!StringUtils.isEmpty(request.getParameter("msg"))) {
            model.addAttribute("msg",request.getParameter("msg"));
        }
        return "zbj/live_marketing_expenses_edit";
    }

    /**
     * 直播营销费用编辑POST
     * @param model
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/live_marketing_expenses_edit",method = RequestMethod.POST)
    public String edit_zhiboPost(Model model,HttpServletRequest request) throws Exception {
        LiveExpensesEntity entity = new LiveExpensesEntity();
        entity.setLiveId(Long.parseLong(request.getParameter("id")));
        Double expenses1 = Double.parseDouble(request.getParameter("expenses1"));
        Double expenses2 = Double.parseDouble(request.getParameter("expenses2"));
        Double expenses3 = Double.parseDouble(request.getParameter("expenses3"));
        Double expenses4 = Double.parseDouble(request.getParameter("expenses4"));
        Double expenses5 = Double.parseDouble(request.getParameter("expenses5"));
        Double expensesTotal = expenses1.doubleValue() + expenses2.doubleValue()+ expenses3.doubleValue()+expenses4.doubleValue()+expenses5.doubleValue();
        entity.setExpenses1(expenses1);
        entity.setExpenses2(expenses2);
        entity.setExpenses3(expenses3);
        entity.setExpenses4(expenses4);
        entity.setExpenses5(expenses5);
        entity.setExpensesTotal(expensesTotal);
        liveDataService.editLiveExpenses(entity);
        return "redirect:/zbj/live_marketing_expenses_edit?id="+entity.getLiveId()+"&msg="+UriEncoder.encode("费用保存成功");
    }


    @RequestMapping(value = "/live_data_del")
    @ResponseBody
    public  ApiResult<String> del(HttpServletRequest req,@RequestParam Long id){
        liveDataService.delLiveData(id);
        return new ApiResult<>(EnumResultVo.SUCCESS.getIndex(),"成功");
    }
//    @RequestMapping(value = "/live_zj", produces = "text/html;charset=UTF-8")
//    @ResponseBody
//    public String getExcelDataByResourceIdAsync() throws IOException {
//
//        // 第一种：获取类加载的根路径   D:\git\daotie\daotie\target\classes
//        String path = this.getClass().getResource("/").getPath();
//        System.out.println(path);
//      String arg1 = path+"\\static\\直播复盘表2022.xlsx";
//        StringBuilder stringBuilder = new StringBuilder();
//        // 打印实现Appendable 接口，可打印到stringbuilder、stringbuffer、BufferedWriter等
//        ExcelToHtml excelToHtml = ExcelToHtml.create(arg1, stringBuilder);
//        excelToHtml.setCompleteHTML(true);// 是否打印完整html
//        excelToHtml.printPage();// 打印
//        System.out.println(stringBuilder.toString());// 输出打印结果
//        return stringBuilder.toString();
//    }


    @ResponseBody
    @RequestMapping(value = "/live_replay_excel_upload", method = RequestMethod.POST)
    public ApiResult<String> live_replay_excel_upload(@RequestParam("excel") MultipartFile file, HttpServletRequest req,@RequestParam Long id) throws IOException, InvalidFormatException {

        String fileName = file.getOriginalFilename();
        String path = this.getClass().getResource("/").getPath() + File.separator;

//        String dir = System.getProperty("user.dir");
//        log.info("根目录"+path);
        String filePath =  path+ "file"+ File.separator+"live_replay"+ File.separator +DateUtil.getCurrentDate()+ File.separator;
        String destFileName = filePath +  fileName;

        File destPath = new File( filePath );
        if (!destPath .exists() && !destPath .isDirectory()){
            log.info("文件夹"+filePath +"不存在，创建");
            destPath.mkdir();
        }
//        System.out.println(destFileName);

        File destFile = new File(destFileName);
        file.transferTo(destFile);

        log.info("/保存文件成功，文件路径" + destFileName + "***********/");

        StringBuilder stringBuilder = new StringBuilder();
        // 打印实现Appendable 接口，可打印到stringbuilder、stringbuffer、BufferedWriter等
        ExcelToHtml excelToHtml = ExcelToHtml.create(destFileName, stringBuilder);
        excelToHtml.setCompleteHTML(true);// 是否打印完整html
        excelToHtml.printPage();// 打印

        //上传文件成功，文件路径插入到数据库
        liveDataService.addLiveReplayFile(id,destFileName);

        return new ApiResult<>(EnumResultVo.SUCCESS.getIndex(),"成功",stringBuilder.toString());
    }
}
